package zy.blue7.gui.netty.custom;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.util.List;

/**
 * @Author: blue7
 * @Date: 2022/2/27 10:21
 * @Version 1.0
 * @Description
 */
@ChannelHandler.Sharable
public class Blue7MessageCodec extends ByteToMessageCodec<Blue7Message> {


    /**
     * todo Encoder : 编码器，将出站的数据从一种格式转换成另外一种格式
     *
     * @param channelHandlerContext
     * @param blue7Message
     * @param byteBuf
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Blue7Message blue7Message, ByteBuf byteBuf) throws Exception {
        /**
         * 获取请求头信息
         */
        Blue7Header blue7Header = blue7Message.getBlue7Header();

        /**
         * 写入Header信息
         */
        byteBuf.writeInt(blue7Header.getVersion());
        byteBuf.writeInt(blue7Header.getContentLength());
        byteBuf.writeBytes(blue7Header.getSessionId().getBytes());

        /**
         * 写入消息主体信息
         */
        byteBuf.writeBytes(blue7Message.getContent().getBytes());
    }

    /**
     * todo Decoder : 解码器，将入站的数据从一种格式转换成另外一种格式。
     *
     * @param channelHandlerContext
     * @param in
     * @param list
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) throws Exception {
        /**
         * 读取版本号
         */
        int version = in.readInt();

        /**
         * 读取 内容长度
         */
        int contentLength = in.readInt();

        /**
         *
         * 获取版本号
         */
        byte[] sessionByte = new byte[36];
        in.readBytes(sessionByte);
        String sessionId = new String(sessionByte);

        /**
         * 组装消息头
         */
        Blue7Header blue7Header = new Blue7Header(version, contentLength, sessionId);

        byte[] content = in.readBytes(in.readableBytes()).array();
        /**
         * 组装消息体
         */
        Blue7Message blue7Message = new Blue7Message(blue7Header, new String(content));

        list.add(blue7Message);
    }

}
